<template lang="pug">
  v-dialog(v-model="active" max-width="500px" persistent)
    v-card
      v-card-title {{ title }}
      v-card-text
        v-form(ref="form")
          v-container
            v-row
              v-col(cols="12")
                v-text-field(ref="inputField"
                  label="名称"
                  v-model="name"
                  :rules="[rules.required]"
                  :error-messages="errorMsg"
                )
              v-col(cols="12")
                v-textarea(ref="inputField" label="描述" v-model="description" )
      v-card-actions
        v-spacer
        v-btn(text @click="toggle") 取消
        v-btn(text color="primary" @click="confirm") 确定
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import rulesMixin from '@/components/mixins/FormValidateRulesMixin'
  import {mapActions} from 'vuex'
  import {AxiosResponse} from 'axios'
  import {get} from 'lodash'

  export default (Vue as VueConstructor<Vue & {
    $refs: {}
  }>).extend({
    mixins: [rulesMixin],
    methods: {
      ...mapActions('assetBundle', ['add']),
      toggle() {
        this.name = ''
        this.description = ''
        this.active = !this.active
      },
      confirm() {
        if (this.$refs.form.validate()) {
          this.$loading('保存中...')
          let data = {
            name: this.name,
            description: this.description
          }
          this.add(data).then((response: AxiosResponse) => {
            if (get(response, 'data.result.error', false)) {
              this.errorMsg = get(response, 'data.result.message', '')
              this.$loading.close()
              return Promise.reject(this.errorMsg)
            }
            this.$emit('refresh')
            this.$loading.close()
            this.toggle()
          })
        }
      }
    },
    data() {
      return {
        active: false,
        name: '',
        description: '',
        title: '新增资产组合',
        errorMsg: null,
      }
    }
  })
</script>
